import React, { useState, useEffect } from 'react'
import { Col, Form, Input, Button, Select, DatePicker, Table, Tag, Modal, Notification, Radio } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import RenderButtom from '@/components/RenderButton'
import SearchBox from '@/components/SearchBox'
import { getPOSList, getSupplierAll, getStoreAll, changeStatus, deletePOS } from '@/services/supplier/store/managePOS'
import { router } from 'umi'

const { RangePicker } = DatePicker
const { Option } = Select
// 表头
const columns = [
  {
    title: '序号',
    dataIndex: 'sort',
    key: 'sort',
    render(text, record, index){
      return <div>{index + 1}</div>
    }
  },
  {
    title: 'POS名称',
    dataIndex: 'posName',
    key: 'posName',
    align: 'center'
  },
  {
    title: '编号/SN',
    dataIndex: 'sn',
    key: 'sn',
    align: 'center'
  },
  {
    title: '所属门店',
    dataIndex: 'storeName',
    key: 'storeName',
    align: 'center',
  },
  {
    title: 'POS类型',
    dataIndex: 'netType',
    key: 'netType',
    render(text, record, index) {
      return <div>{text == 0 ? '线上' : '线下'}</div>
    },
    align: 'center'
  },
  {
    title: 'POS状态',
    dataIndex: 'state',
    key: 'state',
    render(text, record, index) {
      return <div>{text == 0 ? '在线' : text == 1 ? '离线' : '维修'}</div>
    },
    align: 'center'
  },
  {
    title: '当前版本',
    dataIndex: 'version',
    key: 'version',
    align: 'center'
  },
  {
    title: 'IP地址',
    dataIndex: 'ip',
    key: 'ip',
    align: 'center'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center'
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    align: 'center'
  }
]

const ManagePOS = props => {
  const { form } = props
  const { getFieldDecorator } = form
  const [pageNo, setPageNo] = useState(1)
  const [pageSize, setpageSize] = useState(10)
  const [supplierId, setSupplierId] = useState('')
  const [storeId, setStoreId] = useState('')
  const [storeName, setStoreName] = useState('')
  const [posSn, setPosSn] = useState('')
  const [posName, setPosName] = useState('')
  const [version, setVersion] = useState('')
  const [startTime, setStartTime] = useState('')
  const [endTime, setEndTime] = useState('')
  const [state, setState] = useState('')
  const [supplierList, setSupplierList] = useState([])
  const [storeList, setStoreList] = useState([])
  const [POSList, setPOSList] = useState([])
  const [total, setTotal] = useState(1)
  const [modelShow, setModelShow] = useState(false)
  const [record, setRecord] = useState({})
  const [status, setStatus] = useState(1)
  const [statusType, setStatusType] = useState(0)
  const [changeCause, setChangeCause] = useState('')

  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
      // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      console.log(record)
    },
  }

  useEffect(() => {
    init()
  }, [])
  const init = async () => {
    let params = {
      pageNo,
      pageSize
    }
    await getPOSLists(params)
    await getSupplierAlls()
  }
  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      console.log('Received values of form: ', values)

    })
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
  }
  // 查询条件
  const getFields = () => {
    return (
      <Col span={8}>
        <Form.Item label={`商户`}>
          {getFieldDecorator(`supplierId`, {
            initialValue: ""
          })
            (<Select
              showSearch
              filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
              placeholder="请选择"
              onChange={selectSupplier}
            >
              {supplierList && supplierList.map(r => <Option key={r.id} value={r.id}>{r.merchantName}</Option>)}
            </Select>)}
        </Form.Item>
        <Form.Item label={`门店`}>
          {getFieldDecorator(`storeId`, {
            initialValue: ""
          })
            (<Select
              showSearch
              filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
              placeholder="请选择"
            >
              {storeList && storeList.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
            </Select>)}
        </Form.Item>
        <Form.Item label={`门店名称`}>
          {getFieldDecorator(`storeName`, {
            initialValue: ""
          })
            (<Input placeholder="请输入门店" />)}
        </Form.Item>
        <Form.Item label={`POS编号/SN`}>
          {getFieldDecorator(`posSn`, {
            initialValue: ""
          })
            (<Input placeholder="请输入POS编号/SN" />)}
        </Form.Item>
        <Form.Item label={`POS名称`}>
          {getFieldDecorator(`posName`, {
            initialValue: ""
          })
            (<Input placeholder="请输入POS名称" />)}
        </Form.Item>
        <Form.Item label={`APP版本`}>
          {getFieldDecorator(`version`, {
            initialValue: ""
          })
            (<Input placeholder="请输入APP版本" />)}
        </Form.Item>
        <Form.Item label={`创建时间`}>
          {getFieldDecorator(`time`, {
            initialValue: ""
          })
            (<RangePicker onChange={datePicker} />)}
        </Form.Item>
        <Form.Item label={`状态`}>
          {getFieldDecorator(`state`, {
            initialValue: ""
          })
            (<Input placeholder="请输入状态" />)}
        </Form.Item>
      </Col>
    )
  }
  // 按钮处理
  const handleBtn = async type => {
    // console.log(type)
    if (Object.keys(record).length === 0) {
      openNotification()
      return
    }
    switch (type) {
      // 新增POS
      case 1:
      // 跳转到 addPOS 页面
      router.push('/supplier/store/addPOS')
        break
      // 状态变更
      case 12:
        showModal()
        break
      // 删除POS
      case 4:
        let params = {
          id: record[0].id
        }
        console.log(params);
        let res = await deletePOS(params)
        alert(res.msg)
        init()
        break
      // 配置POS
      case 3:
        // 跳转到 addPOS 页面
        router.push({
          pathname: '/supplier/store/addPOS',
          query: {
            POSId: record[0].id
          }
        })
        break
    }
  }
  // 弹出提示选择POS
  const openNotification = () => {
    Notification.open({
      message: '温馨提示',
      description:
        '请选择POS机',
      onClick: () => {
        console.log('Notification Clicked!');
      },
    })
  }
  // 选择评论日期
  const datePicker = (date, dateString) => {
    console.log(date, dateString)
    setStartTimeStr(dateString[0])
    setEndTimeStr(dateString[1])
  }
  // 获取pos列表
  const getPOSLists = async (params) => {
    let res = await getPOSList(params)
    if (res.code === '0') {
      setPOSList(res.data)
      setTotal(res.iTotalDisplayRecords)
    } else {
      alert(res.msg)
    }
  }

  const pagination = {
    total: parseInt(total),
    onChange(page) {
      let params = {
        pageNo: page,
        pageSize
      }
      getPOSLists(params)
    }
  }
  // 获取全部商户
  const getSupplierAlls = async () => {
    let res = await getSupplierAll()
    if (res.code === '0') {
      setSupplierList(res.data)
    } else {
      alert(res.msg)
    }
  }
  // 选择商户
  const selectSupplier = async (value, option) => {
    await getStoreAlls(value)
  }
  // 获取商铺
  const getStoreAlls = async (supplierId) => {
    let params = {
      supplierId,
      pageSize: 999
    }
    let res = await getStoreAll(params)
    if (res.code === '0') {
      setStoreList(res.data)
    } else {
      alert(res.msg)
    }
  }
  const showModal = () => {
    setModelShow(true)
  }
  // 更换状态
  const handleOk = async () => {
    let cause = ''
    form.validateFields((err, values) => {
      cause = values.changeCause
      setChangeCause(cause)
    })
    let params = {
      id: record[0].id,
      reason: cause,
      sn: record[0].sn,
      state: statusType
    }
    let res = await changeStatus(params)
    if (res.code === '0') {
      alert(res.msg)
      init()
    } else {
      alert(res.msg)
    }
    setModelShow(false)
  }
  const handleCancel = e => {
    console.log(e)
    setModelShow(false)
  }
  // 配置POS
  const toSetPOS = () => {
    // 跳转到 addPOS 页面
    router.push('/supplier/store/addPOS')
  }
  // 选择状态
  const selectStatus = e => {
    console.log('radio checked', e.target.value)
    setStatusType(e.target.value)
  }
  return (
    <PageHeaderWrapper>
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table
        columns={columns}
        dataSource={POSList}
        rowKey={record => record.id}
        pagination={pagination}
        rowSelection={rowSelection}
      />
      <Modal
        title="交易设置"
        visible={modelShow}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form.Item label={`状态类型`}>
          {getFieldDecorator(`statusType`, {
            initialValue: 1
          })
            (<Radio.Group onChange={selectStatus}>
              <Radio value={0}>在线</Radio>
              <Radio value={1}>离线</Radio>
              <Radio value={2}>维修</Radio>
              </Radio.Group>)
          }
        </Form.Item>
        <Form.Item label={`更改原因`}>
          {getFieldDecorator(`changeCause`, {
            initialValue: ""
          })
            (<Input placeholder="请输入更改原因" />)}
        </Form.Item>
      </Modal>
   </PageHeaderWrapper>
  )
}

export default Form.create()(ManagePOS)
